import os
import random

class HistoryFile:
    Status_Wait='wait'
    Status_Corrupt='corrupt'
    Status_Success='success'
    
    def __init__(self, filename,split_char='\t',auto_update=False):
        self.filename = filename
        self.history=[]
        self.split_char=split_char
        self.auto_update=auto_update
        self.robustness_ratio=0.1
        
        self.read()
        
    def add_item(self, target,status):
        self.history.append([target,status])
        if self.auto_update:
            self.update(False)
            
    def get_status(self,index):
        return self.history[index][1]
    
    def set_status(self,index,new_status):
        self.history[index][1]=new_status
        if self.auto_update:
            self.update(False)
    
    def change_last_status(self, status):
        self.history[-1][1] = status
        if self.auto_update:
            self.update(False)
            
    @property
    def last_item(self):
        return self.history[-1]
    
    def keys(self):
        return [e[0] for e in self.history]
    
    def values(self):
        return [e[1] for e in self.history]

    def read(self):
        if not os.path.exists(self.filename):
            return
        
        with open(self.filename, 'r') as file:
            self.history=[]
            for line in file:
                target,status=line.strip().split(self.split_char)
                self.history.append([target,status])
            

    def update(self,force=True):
        
        if not force:
            if random.random()<self.robustness_ratio:
                return
        
        with open(self.filename, 'w') as file:
            for target,status in self.history:
                file.write(f'{target}{self.split_char}{status}\n')

    def delete(self):
        if os.path.exists(self.filename):
            os.remove(self.filename)
    
    def __len__(self):
        return len(self.history)
    
    @staticmethod
    def regular(filename,init_handle=None,spliter='\t',auto_update=False):
        if os.path.exists(filename):
            return HistoryFile(filename,spliter,auto_update)
        
        else:
            history=HistoryFile(filename,spliter,False)
            if init_handle:
                items=init_handle()
                for item in items:
                    if isinstance(item,str):
                        history.add_item(item,'')
                    else:
                        key,status=item
                        history.add_item(key,status)
            history.update()
            history.auto_update=auto_update
            return history